package com.xingxue.rbac.service.impl;

import com.xingxue.rbac.dao.OrgDao;
import com.xingxue.rbac.dao.impl.OrgDaoImpl;
import com.xingxue.rbac.entity.Org;
import com.xingxue.rbac.service.OrgService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 实现类2: 基于map查找的实现
 * @author yihang
 */
public class OrgServiceImplMap implements OrgService {
    private OrgDao orgDao = new OrgDaoImpl();

    @Override
    public Collection<Org> findTree() {
        List<Org> all = orgDao.findAll();
        Map<Integer, Org> map = new HashMap<>();
        List<Org> top = new ArrayList<>();
        // 找出顶层集合
        for (Org org : all) {
            map.put(org.getId(), org);
            if (org.getPid() == -1) {
                top.add(org);
            }
        }
        // 根据子元素编号，到map中找到父元素，建立父子关系
        for (Org org : all) {
            Org parent = map.get(org.getPid());
            if (parent != null) {
                parent.getChildren().add(org);
            }
        }
        return top;
    }
}
